import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor, // 拦截器
  HttpRequest, // 请求
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {
  constructor(private message: NzMessageService) {
  }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // req.token = '1111111111111111'
    let token = '123456789'
    let headers = req.headers.set('Authorization', `Bearer ${token}`)
    let secureReq: HttpRequest<any> = req;
    console.log(environment.baseUrl,'secureReq', req.url);
    
    secureReq = secureReq.clone({
      url: environment.baseUrl + req.url,
      headers: headers || null
    });
    return next.handle(secureReq).pipe(
      tap(
        (response: any) => {
          // 处理响应的数据
          console.log(response,'ddddddd')
        },
        (error: any) => {
          // 处理错误的数据
          console.log(error, 'sdf')
          this.message.create('error', error.statusText)
          if(error.status === 401) {
            /**go login */
          } else if (error.status === 404) {
            /**go 404 page */
          }
        }
      )
    )
  }
}